const request = ({
  url,
  method = "POST",
  data,
  headers = {},
  xhrList, // 请求列表 xhr
  onProgress = (e) => e,
}) =>
  new Promise((resolve) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.upload.onprogress = onProgress;
    Object.keys(headers).forEach(
      (key) => xhr.setRequestHeader(key, headers[key]) // 请求头
    );
    xhr.send(data);
    xhr.onload = (e) => {
      // xhr 请求结束
      if (xhrList) {
        const xhrIndex = xhrList.findIndex((item) => item === xhr);
        // 移除 xhr
        xhrList.splice(xhrIndex, 1);
      }
      resolve({
        data: e.target.response,
      });
    };
    if (xhrList) {
      xhrList.push(xhr); // 暴露xhr
      // console.log(xhrList);
    }
  });
export default request;

/**
 * 上传和下载触发的是不同的onprogress事件
 * 上传触发的是 xhr.upload 对象的 onprogress 事件
 * 下载触发的是 xhr 对象上的 onprogress 事件
 *
 * xhr.upload.onprogress 上传
 * xhr.onprogress 下载
 * function onProgress (e) {
 *  e.loaded 已上传
 *  e.total 总共
 *  e.loaded / e.total 进度
 * }
 *
 */
